<?php
use Workerman\Worker;
use Workerman\Lib\Timer;

require_once '../config/config.php';
require_once __DIR__ . '/workerman/Autoloader.php';

$user = array();
$link = array();
$connauth = array();
$ws = new Worker("websocket://0.0.0.0:9999");


$ws->count = 1;

$ws->onConnect = function ($connection) {
    global $connauth;
    $connauth[$connection->id] = Timer::add(15, function () {
        if (isset($connection)) {
            $connection->destroy();
        }
    }, array($connection), false);
};
$ws->onClose = function ($connection) {
    global $user;
    global $link;
    global $_db;
    $_db->exec("delete from uid={$link[$connection->id]}");
    unset($user[$link[$connection->id]]);
    unset($link[$connection->id]);


};

$ws->onMessage = function ($connection, $data) {

    global $user;
    global $link;
    global $connauth;
    global $_db;
    $msg = json_decode($data, true);
    print_r($data);
    if ($msg) {
        switch ($msg['type']) {
            case 'auth': {
                $row = $_db->query("select * from token where `key`='{$msg['token']}'");


                if ($row != false) {
                    $row = $row->fetch();
                    Timer::del($connauth[$connection->id]);
                    $user[$row['uid']] = $connection->id;//uid到连接id
                    $link[$connection->id] = $row['uid'];//连接id到uid
                    $redata = array('type' => 'reauth', 'result' => 1);
                } else {
                    $redata = array('type' => 'reauth', 'result' => 1);

                }
                $connection->send(json_encode($redata));
                break;
            }

            case 'qulist': {
                $ulist = $_db->query("SELECT
	a.fuid,
	a.gid,
	a.memo,
	b.petname,
	b.`name`,
	b.motto,
	b.icon,
	c.`name` as `gname`
FROM
	friend a
LEFT JOIN `user` b ON a.fuid = b.uid
LEFT JOIN `group` c ON a.gid = c.gid and a.uid=c.uid
WHERE
	a.uid ={$link[$connection->id]}");
                $ulist=$ulist->fetchAll(PDO::FETCH_ASSOC);
                foreach ($ulist as $key => $val) {
                    $mes = $_db->query("select * from message WHERE  (`to`='{$val['fuid']}' OR `from`='{$val['fuid']}')")->fetchAll(PDO::FETCH_ASSOC);
                    $ulist[$key]['msg'] = $mes;
                }
                $redata = array('type' => 'relist', 'result' => $ulist);
                $connection->send(json_encode($redata));
//                echo json_encode($redata);
                break;

            }
            case 'message': {
                $time = time();
                $_db->exec("insert into message (msg,`time`, `from`, `to` ) VALUES ('{$msg['data']}',{$time},{$link[$connection->id]},{$msg['to']})");
                $redata['type'] = 'message';
                $connection->send(json_encode($redata));
                if (isset($user[$msg['to']])) {
                    $connection->worker->connections[$user[$msg['to']]]->send(json_encode($redata));
                }
            }

        }


    }


};

// 运行worker
Worker::runAll();